<?php
$field_arr = $_POST['info'];
$role_id_arr = $_POST['role_id'];
$id = $field_arr['id'];
$arr = array (
	'id'
);
$field_arr = arr_diff($field_arr, $arr);
$field_arr = empty2zero($field_arr, array (
	'listorder'
));

$sql = "select id from " . $BIAOTOU . "role where status=1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
	$qx_arr[$row['id']] = 1;
}
if ($id == '') {
	if ($field_arr['parentid'] == 0) // 如果是根级别，不需要判断url
		{
		unset ($field_arr['parentid2']);
		$menuid = insert_one_sql($menu, $field_arr, 0);
		echo alert('根级别保存成功', 'admin.php?act=menulist');
	} else {
		if ($field_arr['parentid2'] == 0) {
			$field_arr['parentid']; //一级有选择，二级为0不选是不替换掉
		} else {
			$field_arr['parentid'] = $field_arr['parentid2']; //偷懒一级换成二级的
		}
		$id = sel_sql($menu, "id", "url='" . $field_arr[url] . "'");
		if ($id) {
			echo alert('操作url已经存在', 'admin.php?act=addmenu');
		} else {
			unset ($field_arr['parentid2']); //把一级父id删掉
			$menuid = insert_one_sql($menu, $field_arr, 0);
		}
	}
	foreach ($role_id_arr as $k => $v) {
		if ($v == 1) {
			if ($field_arr['parentid2']) {
				$arr = array (
					'role_id' => $k,
					'menu_id' => $menuid,
					'parentid' => $field_arr['parentid2']
				);
			} else {
				$arr = array (
					'role_id' => $k,
					'menu_id' => $menuid,
					'parentid' => $field_arr['parentid']
				);
			}
			insert_one_sql('access', $arr, 0);
			unset ($array);
		}
	}
	admin_log('新增后台菜单');
} else {
	$field_arryaunshi[] = $field_arr;
	if ($field_arr['parentid2'] == 0) {
		unset ($field_arr['parentid2']); //把一级父id删掉
	} else {
		$field_arr['parentid'] = $field_arr['parentid2']; //偷懒一级换成二级的
		unset ($field_arr['parentid2']); //把一级父id删掉
	}
	update_sql($menu, $field_arr, "id=$id", 0, 0);
	update_sql('access', array('parentid'=>$field_arr['parentid']), "menu_id=$id", 0, 0);
	foreach ($qx_arr as $k => $v) {
		if ($role_id_arr[$k] == 1) {
			$role_id = sel_sql('access', 'role_id', 'menu_id=' . $id . ' and role_id=' . $k);
			$role_id = $role_id ? $role_id : 0;
			if ($role_id == 0) {
				if ($field_arryaunshi['parentid2']) {
					$arr = array (
						'role_id' => $k,
						'menu_id' => $id,
						'parentid' => $field_arryaunshi['parentid2']
					);
				} else {
					$arr = array (
						'role_id' => $k,
						'menu_id' => $id,
						'parentid' => $field_arryaunshi['parentid']
					);
				}
				insert_one_sql('access', $arr, 0);
			}
		} else {
			$sql = "delete from " . $BIAOTOU . "access where role_id='" . $k . "' and menu_id=" . $id;
			mysql_query($sql);
		}
	}
	admin_log('修改后台菜单');
}
echo alert('保存成功', 'admin.php?act=menulist');
?>
